<script lang="ts">
import Vue from 'vue'
import NavBar from "@/components/nav-bar/nav-bar.vue";
import {copyFun, getPrice, getTypeImage, isMoreThanOneDay} from "@/utils/utils";
import {getRefunds, refundHandle} from "@/services/refund";
import tips from "@/utils/tips";
import {mapState} from "vuex";
import {RefundRecord} from "@/types/store/refund";
import ConfirmPopup from "@/components/confirmPopup/confirmPopup.vue";

export default Vue.extend({
  name: "refund_record",
  components: {ConfirmPopup, NavBar},
  data() {
    return {
      refundOrderList: [] as RefundRecord[],
      confirmPromptShow: false,
      selectedRefundOrder: 0,
      tabsCurrent: 0,
      selectedRefundStatus: 1,

      // 下拉加载
      loading: false,   // 加载状态
      hasMore: true,
      current: 1,   // 当前页码
      pageSize: 10, // 当前页面每页数量
      scrollTop: 0,
      old: {
        scrollTop: 0
      }
    }
  },
  computed: {
    ...mapState(["systemInfo"]),
    lang() {
      return this.$t('storePages.refundRecord')
    },
  },
  onLoad() {
    this.getRefundDataList(this.tabsCurrent)
  },
  onShow(options?: App.LaunchShowOption) {
    this.getRefundDataList(this.tabsCurrent)
  },
  methods: {
    copyFun,
    getPrice,
    getTypeImage,
    isMoreThanOneDay,
    async getRefundDataList(status: number, isButtonLoading = false) {
      this.loading = true
      uni.showLoading({title: '加载中...'})
      const {pageSize, current} = this

      try {
        const {code, data: {data, meta}} = await getRefunds(status, current, pageSize);
        if (code === 200) {
          const {current_page, last_page, next_page} = meta;
          this.current = next_page
          this.refundOrderList = isButtonLoading ? [...this.refundOrderList, ...data] : data

          // 更新是否还有更多数据的标志
          this.hasMore = current_page < last_page
        }
      } catch (error) {
        console.error('加载订单失败:', error);
      } finally {
        this.loading = false;
        uni.hideLoading()
      }
    },
    // 监听滚动
    scroll(e: any) {
      this.old.scrollTop = e.detail.scrollTop
    },
    // scroll 触发
    loadMore() {
      if (!this.loading && this.hasMore) {
        this.getRefundDataList(this.tabsCurrent, true)
      }
    },
    // 头部选择
    onTabs({index}) {
      this.tabsCurrent = index
      // 点击是, 全部返回有元生
      this.refundOrderList = []
      this.current = 1
      this.hasMore = true

      // 解决view层不同步的问题
      this.scrollTop = this.old.scrollTop
      this.$nextTick(() => {
        this.scrollTop = 0
      });
      this.getRefundDataList(index)
    },
    // 详情
    async onItem(id: string) {
      uni.navigateTo({url: '/pages/store/order/refund_order_detail?id=' + id})
    },
    // 弹窗显示
    onConfirmPromptShow(orderId: number, status: number) {
      this.selectedRefundOrder = orderId
      this.selectedRefundStatus = status
      this.confirmPromptShow = true
    },
    // 处理函数
    async confirmRefund() {
      const {selectedRefundOrder, selectedRefundStatus} = this
      if (selectedRefundStatus === 0) {
        tips.toast('请选择退款状态')
        return
      }
      this.confirmPromptShow = false
      uni.showLoading({title: '处理中...'})
      try {
        const res = await refundHandle(selectedRefundOrder, selectedRefundStatus)
        if (res.code === 200) {
          this.refundOrderList = this.refundOrderList.filter(order => order.id !== selectedRefundOrder)
          tips.toast(res.msg)
        }
      } finally {
        uni.hideLoading()
      }
    },
  }
})
</script>

<template>
  <view>
    <!-- 退款记录-->
    <nav-bar :pageTitle="lang.pageName" navbar-color="#fff"/>
    <view :class="['margin-20', locale]">
      <u-sticky :customNavHeight="systemInfo.statusBarHeight + 56">
        <view class="radio-20 padding-20 bg-white">
          <u-tabs :list="lang.tabs" :scrollable="false" :lineWidth="28" :activeStyle="{ color: '#0186FF' }"
                  @click="onTabs" :current="0"/>
        </view>
      </u-sticky>
      <view style="height: 20rpx"/>

      <scroll-view scroll-y class="scroll-view" @scrolltolower="loadMore" :scroll-top="scrollTop" @scroll="scroll">
        <template v-if="refundOrderList.length >= 1">
          <!-- order-->
          <view v-for="(item, index) in refundOrderList" :key="index">
            <view class="radio-20 padding-30 bg-white gap-20 flex-column" style="margin:20rpx 0 20rpx 0"
                  @click="onItem(item.id)">
              <view class="flex-between">
                <view @longpress="copyFun(item.order.order_number)" class="text-32">
                  {{ item.order.order_number }}
                </view>

                <!-- 完成或退款-->
                <view
                    :class="['default-text label', item.refund_status === 0 ? 'treat_refunded' : (item.refund_status === 1 ? 'preview-label':(item.refund_status === 2 ? 'refunded':''))]">
                  {{
                    lang.status[item.refund_status === 0 ? 'pending' : (item.refund_status === 1 ? 'refunded' : (item.refund_status === 2 ? 'rejected' : ''))]
                  }}
                </view>
              </view>

              <view class="line"/>
              <!-- 订单信息-->
              <view class="flex-center gap-20 default-text">
                <view :class="['padding-30 radio-20 center type', getTypeImage(item.order.ext)]">
                  <image :src="`/static/ext/${getTypeImage(item.order.ext)}.svg`" class="resources-image"/>
                </view>
                <view class="column flex-1 gap-20">
                  <view class="flex-between">
                    <view>{{ lang.orderInfo['totalPrice'] }}</view>
                    <view class="flex-center ltr color-black">
                      <u-icon name="rmb" :size="16" color="#000"/>
                      {{ getPrice(item.refund_amount) }}
                    </view>
                  </view>
                  <view class="flex-between">
                    <view>{{ lang.orderInfo['printPages'] }}</view>
                    <view class="color-black">
                      {{ item.order.page }}x{{ item.order.paper_count }}{{ otherLang.page }}
                    </view>
                  </view>
                  <view class="flex-between">
                    <view>{{ lang.orderInfo['refundTime'] }}</view>
                    <view class="color-black">{{ item.created_at }}</view>
                  </view>
                  <view v-if="item.phone_number" class="flex-between" @longpress="copyFun(item.phone_number)">
                    <view>{{ lang.orderInfo['refundPhone'] }}</view>
                    <view class="color-black">{{ item.phone_number }}</view>
                  </view>
                </view>
              </view>

              <!-- 退款-->
              <view class="flex-end default-text gap-20" v-if="item.refund_status == 0">
                <view :class="['tab-label refunded']" style="border: none"
                      @click.stop="onConfirmPromptShow(item.id,2)">
                  {{ lang.operations['reject'] }}
                </view>

                <view :class="['tab-label preview-label']" @click.stop="onConfirmPromptShow(item.id,1)">
                  {{ lang.operations['refund'] }}
                </view>
              </view>
            </view>
          </view>
          <!-- 底部提示-->
          <view class="margin-top-40 color-grey common-title safe-area-padding" style="width: 100%;">
            <view v-if="loading" class="center gap-20">
              <u-loading-icon/>
              <view>{{ otherLang.loading }}</view>
            </view>
            <view v-if="!loading && !hasMore" class="flex-between">
              <view class="line-weight-30"/>
              <view>{{ otherLang.no_more }}</view>
              <view class="line-weight-30"/>
            </view>
          </view>
        </template>

        <!-- 空数据-->
        <view v-if="refundOrderList.length <= 0" class="center" style="height: 60vh;">
          <u-empty
              mode="order"
              :width="240"
              :hidden="240"
              :textSize="22"
              :text="lang.emptyData"
              icon="http://cdn.uviewui.com/uview/empty/order.png"
          />
        </view>
      </scroll-view>
    </view>

    <!-- 退款-->
    <confirm-popup
        :title="lang.modal['title']" :show="confirmPromptShow" @update:show="confirmPromptShow = false"
        @confirm="confirmRefund"
    >
      <view class="center default-text line-height-one-six">
        {{ lang.modal[selectedRefundStatus === 1 ? 'confirmRefund' : 'confirmReject'] }}
      </view>
    </confirm-popup>
  </view>
</template>

<style scoped lang="scss">

</style>